package com.dream.inspect.modules.business.common;

import com.dream.inspect.common.utils.StringUtil;
import com.dream.inspect.modules.business.dao.SuperviseStandardDao;
import com.dream.inspect.modules.sys.controller.AbstractController;
import com.dream.inspect.modules.sys.dao.SysDeptDao;
import com.dream.inspect.modules.sys.entity.SysDeptEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公用方法bean
 */
@Component
public class CommonComponent extends AbstractController {
    @Autowired
    private SysDeptDao sysDeptDao;
    @Autowired
    private SuperviseStandardDao superviseStandardDao;

    /**
     * 获取当前和所有上级单位id集
     */
    public String findParentIds(Long deptId) {
        //String deptIds="0";
        Map<Long, Object> deptIdMap = new HashMap<Long, Object>();
        getParentIds(deptIdMap, deptId);
        String deptIds = "";
        for (Long corpId : deptIdMap.keySet()) {
            if (deptIds != "") {
                deptIds += ",";
            }
            deptIds += corpId;
        }

        return deptIds;
    }

    /**
     * 递归获取父id
     *
     * @param deptIds
     * @param deptId
     */
    public void getParentIds(Map<Long, Object> deptIds, Long deptId) {
        SysDeptEntity sysDeptEntity = sysDeptDao.selectById(deptId);
        //deptIds+=","+deptId;
        deptIds.put(deptId, sysDeptEntity);
        if (sysDeptEntity.getParentId() != 0) {
            getParentIds(deptIds, sysDeptEntity.getParentId());
        }
    }

    /**
     * 获取下一个编号
     *
     * @param level
     * @param parentCode
     * @return
     */
    public String getNextCode(String level, String parentCode) {
        StringBuffer code = new StringBuffer("0");
        List<String> maxCodeList = superviseStandardDao.findMaxCodeByLevelAndCode(parentCode, level);
        String maxCode = "00000000";
        if (maxCodeList != null && maxCodeList.size() > 0) {
            maxCode = maxCodeList.get(0);

        }
        if(StringUtil.isEmpty(maxCode)){
            maxCode = parentCode;
        }
        if ("1".equals(level)) {
            code.append((Integer.parseInt(maxCode) + 1000000));
        } else if ("2".equals(level)) {
            code.append((Integer.parseInt(maxCode) + 10000));
        } else if ("3".equals(level)) {
            code.append((Integer.parseInt(maxCode) + 100));
        } else if ("4".equals(level)) {
            code.append((Integer.parseInt(maxCode) + 1));
        }

        return code.toString();
    }
}
